package com.shioirikukuri.service.impl;

import com.shioirikukuri.entity.Setmeal;
import com.shioirikukuri.entity.SetmealFood;
import com.shioirikukuri.mapper.SetmealFoodMapper;
import com.shioirikukuri.mapper.SetmealMapper;
import com.shioirikukuri.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SetmealServiceImpl implements ISetmealService {

	@Autowired
	private SetmealMapper setmealMapper; // 注入SetmealMapper用于套餐的基本操作

	@Autowired
	private SetmealFoodMapper setmealFoodMapper; // 注入SetmealFoodMapper用于套餐-菜品关联操作

	@Override
	public List<Setmeal> getAllSetmeals() {
		return setmealMapper.selectAllSetmeals();
	}

	@Override
	public Optional<Setmeal> getSetmealById(Long id) {
		// 返回套餐基本信息，调用者需要通过SetmealFoodMapper获取foodIds
		return Optional.ofNullable(setmealMapper.selectSetmealById(id));
	}

	@Override
	public Setmeal addSetmeal(Setmeal setmeal, List<Long> foodIds) {
		// 插入套餐基本信息
		setmealMapper.insertSetmeal(setmeal);

		// 假设insertSetmeal方法设置了setmeal的ID
		if (foodIds != null && !foodIds.isEmpty()) {
			for (Long foodId : foodIds) {
				SetmealFood setmealFood = new SetmealFood(setmeal.getId(), foodId);
				setmealFoodMapper.insert(setmealFood);
			}
		}

		return setmeal;
	}

	@Override
	public Setmeal updateSetmeal(Long id, Setmeal setmeal, List<Long> foodIds) {
		setmeal.setId(id); // 确保更新的是指定ID的记录

		// 更新套餐基本信息
		setmealMapper.updateSetmeal(setmeal);

		// 先删除旧的关联数据，再插入新的关联数据
		setmealFoodMapper.deleteBySetmealId(id);
		if (foodIds != null && !foodIds.isEmpty()) {
			for (Long foodId : foodIds) {
				SetmealFood setmealFood = new SetmealFood(id, foodId);
				setmealFoodMapper.insert(setmealFood);
			}
		}

		// 仅返回套餐基本信息，不包含foodIds
		return setmeal;
	}

	@Override
	public void deleteSetmeal(Long id) {
		// 删除套餐与菜品的关联信息
		setmealFoodMapper.deleteBySetmealId(id);

		// 删除套餐基本信息
		setmealMapper.deleteSetmealById(id);
	}
}